package com.dmatek.uwb.util.tool;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/***
 * 网络工具
 * @author zhangfu
 * @data 2019年6月22日 下午3:04:01
 * @Description
 */
public final class NetWorkUtil {
	/***
	 * 获取本机所有的ipv4
	 * @return
	 * @throws SocketException
	 */
	public static List<String> getAllIps() throws SocketException {
		List<String> ips = new ArrayList<String>();
		Enumeration<NetworkInterface> enumerations = NetworkInterface.getNetworkInterfaces();
		while (enumerations.hasMoreElements()) {
			NetworkInterface netWorkInterface = enumerations.nextElement();
			Enumeration<InetAddress> addressEnum = netWorkInterface.getInetAddresses();
			while(addressEnum.hasMoreElements()) {
				InetAddress inetAddress = addressEnum.nextElement();
				if(null != inetAddress && inetAddress instanceof Inet4Address) {
					String ip = inetAddress.getHostAddress();
					if(!StringUtil.isEmpty(ip)) {
						ips.add(ip);
					}
				}
			}
		}
		return ips;
	}
	/***
	 * 判断当前的ip是否是本机ipv4地址
	 * @param ip
	 * @return
	 * @throws SocketException 
	 */
	public static boolean isLocalIp(String ip) throws SocketException {
		List<String> ips = getAllIps();
		for (String string : ips) {
			if(string.equalsIgnoreCase(ip)) {
				return true;
			}
		}
		return false;
	}
}
